import ctypes
import sys
import subprocess
import random
import time

def is_admin():
    """检查是否以管理员权限运行"""
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def run_as_admin():
    """以管理员权限重新运行脚本"""
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
    sys.exit()

def random_mac():
    """生成随机的本地管理MAC地址"""
    # 第一个字节的bit 1（从0开始）设为1，即0x02, 0x06, 0x0A, 0x0E等
    first_byte = random.randint(0x00, 0xFF)
    first_byte = (first_byte & 0xFE) | 0x02  # 确保bit 1为1
    mac_bytes = [
        first_byte,
        random.randint(0x00, 0xFF),
        random.randint(0x00, 0xFF),
        random.randint(0x00, 0xFF),
        random.randint(0x00, 0xFF),
        random.randint(0x00, 0xFF)
    ]
    mac = ":".join("{:02X}".format(b) for b in mac_bytes)
    return mac

def set_mac(interface_name, new_mac):
    """使用PowerShell设置MAC地址"""
    try:
        subprocess.run(
            [
                "powershell",
                "Set-NetAdapterAdvancedProperty",
                "-Name", f'"{interface_name}"',
                "-RegistryKeyword", "NetworkAddress",
                "-RegistryValue", new_mac
            ],
            check=True,
            shell=True
        )
    except subprocess.CalledProcessError as e:
        print(f"设置MAC地址失败: {e}")
        raise

def restart_interface(interface_name):
    """重启网络接口"""
    try:
        subprocess.run(
            ["netsh", "interface", "set", "interface", f'name="{interface_name}"', "admin=disable"],
            check=True,
            shell=True
        )
        time.sleep(5)  # 等待接口禁用
        subprocess.run(
            ["netsh", "interface", "set", "interface", f'name="{interface_name}"', "admin=enable"],
            check=True,
            shell=True
        )
    except subprocess.CalledProcessError as e:
        print(f"重启接口失败: {e}")
        raise

def main():
    # 检查管理员权限
    if not is_admin():
        print("请求管理员权限...")
        run_as_admin()

    interface_name = "WLAN"  # 更改为你的接口名称，如“以太网”
    interval = 60  # 间隔时间（秒），例如3600为一小时

    try:
        while True:
            new_mac = random_mac()
            print(f"尝试更改MAC地址为: {new_mac}")
            set_mac(interface_name, new_mac)
            restart_interface(interface_name)
            print(f"成功更改MAC地址，下次更改将在{interval}秒后执行")
            time.sleep(interval)
    except KeyboardInterrupt:
        print("\n脚本已停止")

if __name__ == "__main__":
    main()
    time.sleep(10)